package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Resource
    private ApArticleContentMapper apArticleContentMapper;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private ApArticleService apArticleService;
    @Resource
    private Configuration configuration;
    /**
     * 生成静态文件上传到MinIo中
     *
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIo(ApArticle apArticle, String content) {
        Template template = null;
        StringWriter out = new StringWriter();
        try {
            template  = configuration.getTemplate("article.ftl");
            // 数据模型
            Map<String, Object> contentDataModel = new HashMap<>();
            contentDataModel.put("content", JSONArray.parseArray(content));
            template.process(contentDataModel,out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 把html上传到minio中
        ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes());
        String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);
        apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,apArticle.getId())
                .set(ApArticle::getStaticUrl,path));


    }
}
